package core;

import Utils.addUtils;
import Utils.commitUtils;
import Utils.tempWorkTree;
import fileoperation.FileCreation;
import fileoperation.FileReader;
import gitobject.Blob;
import gitobject.Commit;
import gitobject.GitObject;
import gitobject.Tree;
import repository.Repository;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class JitCommit {
    public static String tempCommitpath;
    public static String lastIndex;

    //提交文件
    public static void commit(String filePath) throws Exception {
        tempWorkTree.updateWorkTree();

        tempCommitpath=filePath;

        String headKey= Commit.getLastCommit();
        Commit tempcommit = Commit.deserialize(headKey);
        if(tempcommit==null){
            lastIndex="";
        }else{
            String tree = tempcommit.getTree();
            Tree t=Tree.deserialize(tree);
            lastIndex= FileCreation.getlastIndex(t,tempWorkTree.workTree);
        }
        File file = new File(filePath);
        if((!file.exists())||!(addUtils.readAllIndex(tempWorkTree.indexLoc).contains(file.getPath()))){
            System.out.println("this file is unknown to jit");
            return;
        }
        commitDetail(filePath);
    }

    public static void commitDetail(String filePath) throws Exception {
        commitUtils.checkAndUpdateIndex();
        addUtils.serFiles();
        Tree tree= commitUtils.rootFloor();
        Commit commit = new Commit(tree, "", "", "");

        Commit precommit=Commit.deserialize(commit.getParent());

        File file = new File(tempWorkTree.indexLoc);
        if((FileReader.readFileByBytes(file).length<=10)||(precommit!=null&&precommit.getTree().equals(tree.getKey()))){
            
            JitStatus.status();
            return;
        }
      
        tree.writeObject();
       
        commit.writeObject();
       

        String branchName=JitBranch.getBranchName(tempWorkTree.gitDir);
        FileOutputStream fileOutputStream = new FileOutputStream(tempWorkTree.logHead, true);
        FileOutputStream historyOut = new FileOutputStream(tempWorkTree.commitHistoryLoc+File.separator+branchName, true);
        FileOutputStream curOut = new FileOutputStream(tempWorkTree.lastCommitLoc+File.separator+branchName, false);
        String parent=commit.getParent().equals("")?"0000000000000000000000000000000000000000":commit.getParent();
        String temp1=parent+" "+commit.getKey()+" commit "+commit.getTime()+"\n";
        String temp2=commit.getKey();
        fileOutputStream.write(temp1.getBytes(StandardCharsets.UTF_8));
        historyOut.write(temp1.getBytes(StandardCharsets.UTF_8));
        curOut.write(temp2.getBytes(StandardCharsets.UTF_8));
        fileOutputStream.close();
        historyOut.close();
        curOut.close();
        tempCommitpath="";
        lastIndex="";
       
    }



}
